<template>
  <div class="main-content">
    <div class="top">
      <div class="top-op">
        <div class="search-panel">
          <!-- 搜索框 -->
          <el-input v-model="searchName" clearable placeholder="搜索用户名" @keyup.enter="searchUsers">
            <template #suffix>
              <i class="iconfont icon-search" @click="searchUsers"></i>
            </template>
          </el-input>
        </div>
        <div class="iconfont icon-refresh" @click="refreshUserList"></div>
      </div>
      <div>用户列表 ({{ total }}个)</div>
    </div>

    <!-- 用户列表 -->
    <div class="user-list" v-if="userList.length > 0">
      <el-table :data="userList" style="width: 100%">
        <el-table-column label="用户信息" min-width="300">
          <template #default="{ row }">
            <div class="user-name-cell">
              <div class="user-avatar">
                <img :src="row.qqAvatar" alt="用户头像" class="avatar">
              </div>
              <span class="nick-name" :title="row.nickName">{{ row.nickName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="空间使用" width="250">
          <template #default="{ row }">
            <div class="space-usage">
              <div class="space-text">
                <span>{{ formatFileSize(row.usedSpace) }} / {{ formatFileSize(row.totalSpace) }}</span>
              </div>
              <el-progress :percentage="Math.floor((row.usedSpace / row.totalSpace) * 100) || 0" color="#409eff"
                :stroke-width="8" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="最后登录时间" width="200">
          <template #default="{ row }">
            {{ formatDate(row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <div class="user-actions">
              <el-button :type="row.status === 1 ? 'danger' : 'success'" size="small"
                @click.stop="toggleUserStatus(row)">
                {{ row.status === 1 ? '禁用' : '恢复' }}
              </el-button>
              <el-button type="primary" size="small" @click.stop="adjustUserSpace(row)">调整空间</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[8, 16, 24, 36]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 无数据提示 -->
    <div v-else class="no-data">
      <div class="no-data-inner">
        <img src="@/assets/empty.png" alt="暂无数据" width="200">
        <div class="tips">暂无用户数据</div>
      </div>
    </div>
  </div>

  <!-- 调整空间对话框 -->
  <el-dialog v-model="dialogVisible" title="调整用户空间" width="400px">
    <div v-if="currentUser" class="dialog-content">
      <div class="user-info">
        <img :src="currentUser.qqAvatar" alt="用户头像" class="avatar">
        <div class="nick-name">{{ currentUser.nickName }}</div>
      </div>

      <div class="space-options">
        <span>选择空间调整：</span>
        <el-radio-group v-model="spaceChange" size="small">
          <el-radio-button :label="-100">-100 MB</el-radio-button>
          <el-radio-button :label="-50">-50 MB</el-radio-button>
          <el-radio-button :label="50">+50 MB</el-radio-button>
          <el-radio-button :label="100">+100 MB</el-radio-button>
        </el-radio-group>
      </div>

      <div class="space-info">
        <span>当前空间：</span>
        <span>{{ formatFileSize(currentUser.totalSpace) }}</span>
      </div>

      <div class="space-info">
        <span>调整后空间：</span>
        <span>{{ formatFileSize(Math.max(0, currentUser.totalSpace + spaceChange * 1024 * 1024)) }}</span>
      </div>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitSpaceChange">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { getAllUserInfoService, updateUserStatusService, updateUserTotalSpaceService } from "@/api/user.js";
import { ElMessage, ElMessageBox, ElDialog, ElRadioGroup, ElRadioButton } from 'element-plus';
import { ref, onMounted } from "vue";

const userList = ref([]);
const currentPage = ref(1);
const pageSize = ref(8);
const total = ref(0);
const searchName = ref('');

// 调整空间对话框相关变量
const dialogVisible = ref(false);
const currentUser = ref(null);
const spaceChange = ref(50); // 默认50MB

// 加载用户列表
const loadUserList = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };

    // 添加搜索条件
    if (searchName.value) {
      params.name = searchName.value;
    }

    const result = await getAllUserInfoService(params);
    if (result && result.data) {
      userList.value = result.data.records || [];
      total.value = result.data.total || 0;
    }
  } catch (error) {
    console.error('加载用户列表失败:', error);
    ElMessage.error('加载用户列表失败');
  }
};

// 搜索用户
const searchUsers = () => {
  currentPage.value = 1; // 搜索时重置页码
  loadUserList();
};

// 刷新用户列表
const refreshUserList = () => {
  loadUserList();
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  loadUserList();
};

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadUserList();
};

// 切换用户状态（禁用/恢复）
const toggleUserStatus = async (user) => {
  const action = user.status === 1 ? '禁用' : '恢复';
  ElMessageBox.confirm(
    `确定要${action}用户 ${user.nickName} 吗？`,
    `${action}确认`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: user.status === 1 ? 'warning' : 'info',
    }
  ).then(async () => {
    try {
      await updateUserStatusService(user.id);
      ElMessage.success(`${action}成功`);
      // 直接更新本地状态，避免重新加载整个列表
      user.status = user.status === 1 ? 0 : 1;
    } catch (error) {
      console.error(`${action}用户失败:`, error);
      ElMessage.error(`${action}用户失败`);
    }
  }).catch(() => {
    // 取消操作
  });
};

// 打开调整空间对话框
const adjustUserSpace = (user) => {
  currentUser.value = user;
  spaceChange.value = 50; // 重置为默认值
  dialogVisible.value = true;
};

// 提交空间调整
const submitSpaceChange = async () => {
  if (!currentUser.value) return;

  try {
    // 计算调整后的空间
    const newTotalSpace = currentUser.value.totalSpace + spaceChange.value * 1024 * 1024;

    // 确保空间不会变为负数
    if (newTotalSpace < 0) {
      ElMessage.warning('调整后空间不能为负数');
      return;
    }

    const dto = {
      id: currentUser.value.id,
      space: spaceChange.value // 直接传递MB数值
    };

    await updateUserTotalSpaceService(dto);
    ElMessage.success('空间调整成功');
    dialogVisible.value = false;

    // 更新本地用户数据
    currentUser.value.totalSpace = newTotalSpace;
  } catch (error) {
    console.error('调整空间失败:', error);
    ElMessage.error('调整空间失败');
  }
};

// 格式化日期时间
const formatDate = (date) => {
  if (!date) return '从未登录';

  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return '0 B';

  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let index = 0;
  let fileSize = size;

  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024;
    index++;
  }

  return `${fileSize.toFixed(2)} ${units[index]}`;
};

onMounted(() => {
  loadUserList();
});
</script>

<style lang="scss" scoped>
@import "@/assets/file.list.scss";

.main-content {
  height: 100%;
  overflow: auto;
}

.user-list {
  margin-top: 20px;

  .user-name-cell {
    display: flex;
    align-items: center;
    gap: 10px;

    .user-avatar {
      width: 40px;
      height: 40px;
      flex-shrink: 0;
    }

    .avatar {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      object-fit: cover;
    }

    .nick-name {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #333;
      font-weight: 500;
    }
  }

  .space-usage {
    .space-text {
      font-size: 12px;
      color: #666;
      margin-bottom: 5px;
      text-align: left;
    }
  }

  .user-actions {
    display: flex;
    gap: 8px;

    .el-button {
      font-size: 12px;
      padding: 4px 8px;
    }
  }

  :deep(.el-table) {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.no-data {
  height: calc(100vh - 200px);
  display: flex;
  align-items: center;
  justify-content: center;

  .no-data-inner {
    text-align: center;

    .tips {
      margin-top: 20px;
      color: #999;
    }
  }
}

.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;

  .top-op {
    display: flex;
    align-items: center;

    .search-panel {
      margin-right: 20px;
      width: 300px;
    }

    .icon-refresh {
      cursor: pointer;
      font-size: 20px;
      color: #666;
    }
  }
}

/* 对话框样式 */
.dialog-content {
  padding: 10px 0;

  .user-info {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .avatar {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      margin-right: 15px;
      object-fit: cover;
    }

    .nick-name {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .space-options {
    margin-bottom: 20px;
  }

  .space-info {
    margin-bottom: 10px;
    font-size: 14px;
  }
}
</style>
